//
//  SRSpeakingTestViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/4/20.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRSpeakingTestViewController.h"

#import "SRSpeakingTestTableViewCell.h"
#import "SRSpeakingTestDoneTableViewCell.h"
#import "SRWorkShareView.h"


#import "SRWordTranslateView.h"
#import "SRSpeakingTestModel.h"
#import "SRBookPageTrackItemModel.h"

#import "SRCommonConstants.h"
#import "SREvaluationScoreModel.h"
//#import "SREvaluationManager.h"
#import "SRSpeakingDatabaseManager.h"
#import "FZMCCacheManager.h"
#import "SRAudioPlayerManager.h"
#import "SRAlbumService.h"
#import "SRUploadQiniuManager.h"
#import <FZCommonShare.h>
#import <lame/lame.h>
#import <AudioToolbox/AudioToolbox.h>
#import "AudioMerger.h"

#import "UIAlertView+SRBlocks.h"
#import "SRYoudaoTranslateRootModel.h"
#import "SRYoudaoTranslateBasicModel.h"
#import "SRWorkDetailViewController.h"
#import "SingSound/SSOralEvaluatingManager.h"
#import "SRSpeakingTestScoreHeaderView.h"
#import "SRClassConstants.h"
#import "SREvaluationWordScoreModel.h"

@interface SRSpeakingTestViewController ()<UITableViewDataSource,UITableViewDelegate, SSOralEvaluatingManagerDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) UIView *wordTranslateBgView;
@property (strong, nonatomic) SRWordTranslateView *wordTranslateView;//单词翻译
@property (strong, nonatomic) UIView *shareBackgroundView;
@property (strong, nonatomic) SRWorkShareView *popShareView;

@property (strong, nonatomic) SRSpeakingTestScoreHeaderView *scoreHeaderView;


@property (strong, nonatomic) SRSpeakingTestModel *speadkingModel;
@property (strong, nonatomic) NSDictionary *sentenceScoreDict;
@property (copy, nonatomic) NSDictionary *draftWordScore;

@property (strong, nonatomic) SRSpeakingTestTableViewCell *targetCell;
@property (strong, nonatomic) NSIndexPath *targetIndexPath;
//@property (strong, nonatomic) SREvaluationManager *evaluationManager;
@property (assign, nonatomic) BOOL isEvaluating;//正在评分
@property (assign, nonatomic) BOOL didSaveToDatabase;//已经保存到数据库

@property (strong, nonatomic) SRBookPageTrackItemModel *shareTrackModel;
@property (strong, nonatomic) NSString *mp3FilePath;
@property (strong, nonatomic) NSString *audioFileName;
@property (strong, nonatomic) NSString *shareURL;

@property (assign, nonatomic) NSInteger recordCount;//录音句子数
@property (strong, nonatomic) NSMutableDictionary *trackTimesDict;

@property (assign, nonatomic) BOOL isComposeWork;
@property (strong, nonatomic) NSString *uploadWorkID;
@property (strong, nonatomic) NSString *uploadWorkShareURL;
@property (assign, nonatomic) NSInteger workScore;

@end

@implementation SRSpeakingTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"配音";
    [self setupData];
    [self setupView];
    
    if ([self.items count] > 0) {
        
        self.title = [NSString stringWithFormat:@"%@ (0/%lu)", self.catalogueModel.title, (unsigned long)[self.items count]];
        [self.tableView reloadData];
     
        [self canRecord];
    } else {
        [self emptyLoadingViewWithTitle:@"该页没有可评测的句子，到其他页看看吧"];
    }
    [SSOralEvaluatingManager shareManager].delegate = self;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [SSOralEvaluatingManager shareManager].delegate = nil;

    [[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];
    if (!self.didSaveToDatabase) {
        [self calculateScoresToModel];
        [self saveSpeakingTestModelToDatabase];
    }
}

- (void)doBack {
    [[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];
    self.didSaveToDatabase = YES;
    [self calculateScoresToModel];
    [self saveSpeakingTestModelToDatabase];
    
    [super doBack];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (self.targetIndexPath && [self.items count] > self.targetIndexPath.row) {
        SRBookPageTrackItemModel *lastModel = self.items[self.targetIndexPath.row];
        lastModel.isExpand = YES;
        [self.tableView reloadRowsAtIndexPaths:@[self.targetIndexPath] withRowAnimation:UITableViewRowAnimationNone];
        [self onTouchOriginPlayButton:nil trackModel:lastModel];
		
		[self.scoreHeaderView updateCellInfoForScore:lastModel.scoreModel];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];
    self.didSaveToDatabase = YES;
    [self calculateScoresToModel];
    [self saveSpeakingTestModelToDatabase];
    
}


#pragma mark - setup

- (void)setupData {
        //test dat
    self.recordCount = 0;
    self.targetIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];//默认选中第一个
//    self.evaluationManager = [SREvaluationManager sharedManager];
//    [self.evaluationManager setEvaluationSupplier:FZDubEvaluationSupplierIfly language:SRSpeakingEvaluationTextTypeEnglish];
//    self.evaluationManager.delegate = self;
    [self getDraftScoreData];
}

- (void)setupView {
    
    WEAKSELF
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
	
	self.scoreHeaderView = [[[NSBundle mainBundle] loadNibNamed:@"SRSpeakingTestScoreHeaderView" owner:nil options:nil] firstObject];
	self.scoreHeaderView.didChangeWordHeightBlock = ^(CGFloat wordHeight) {
		[weakSelf.scoreHeaderView mas_updateConstraints:^(MASConstraintMaker *make) {
//			make.leading.trailing.equalTo(self.view);
//			make.top.equalTo(self.view);
			make.height.mas_equalTo(92+wordHeight);
		}];
	};
	[self.scoreHeaderView setCount:[self.items count]];
	[self.scoreHeaderView setIndex:0];
	
	[self.view addSubview:self.scoreHeaderView];
	[self.scoreHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.leading.trailing.equalTo(self.view);
		make.top.equalTo(self.view);
		make.height.mas_equalTo(180);
	}];
	
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 60;
    
    [self.tableView registerNib:[UINib nibWithNibName:kSRSpeakingTestTableViewCell bundle:nil] forCellReuseIdentifier:kSRSpeakingTestTableViewCell];
    [self.tableView registerNib:[UINib nibWithNibName:kSRSpeakingTestDoneTableViewCell bundle:nil] forCellReuseIdentifier:kSRSpeakingTestDoneTableViewCell];

    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.top.equalTo(self.scoreHeaderView.mas_bottom);
        make.leading.trailing.bottom.equalTo(self.view);
    }];
    self.view.backgroundColor = self.tableView.backgroundColor = css.color_2;
    
    self.wordTranslateBgView = [[UIView alloc] init];
    self.wordTranslateBgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
    [self.wordTranslateBgView addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
        [weakSelf hideTranslateView];
    }];
    
    [self.view addSubview:self.wordTranslateBgView];
    [self.wordTranslateBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.wordTranslateView = [[[NSBundle mainBundle] loadNibNamed:@"SRWordTranslateView" owner:nil options:nil] firstObject];
    
    [self.view addSubview:self.wordTranslateView];
    
    [self.wordTranslateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.height.mas_equalTo(275);
    }];
    
    self.wordTranslateBgView.hidden = YES;
    self.wordTranslateView.hidden = YES;
    
    self.shareBackgroundView = [[UIView alloc] init];
//    [self.shareBackgroundView addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
//        [weakSelf hideShareView];
//    }];
    
    self.shareBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.75];
    [self.view addSubview:self.shareBackgroundView];
    self.shareBackgroundView.hidden = YES;
}


- (SRWorkShareView *)popShareView {
    if (!_popShareView) {
        _popShareView = [[[NSBundle mainBundle] loadNibNamed:@"SRWorkShareView" owner:nil options:nil] firstObject];
        CGFloat width = MIN(SCREEN_WIDTH - 20, 320);
        
        _popShareView.frame = CGRectMake(0, 0, width, 250);
        
        [self.view addSubview:_popShareView];
        _popShareView.center = CGPointMake(SCREEN_WIDTH / 2.0, CGRectGetHeight(self.view.frame) / 2.0);
        
        WEAKSELF
        _popShareView.touchShareBlock = ^(FZCommonShareSocialSNSType socialType) {
            
//            [weakSelf hideShareView];
//            [weakSelf shareTrackModelWithShareUrl:weakSelf.shareURL snsType:socialType];
            [weakSelf shareAudioWorkWithShareUrl:weakSelf.uploadWorkShareURL workID:weakSelf.uploadWorkID snsType:socialType];
        };
        
        _popShareView.touchShowWorkBlock = ^(id sender) {
//            [weakSelf hideShareView];
            [weakSelf showRecordWork];
        };
    }
    
    return _popShareView;
}

#pragma mark - Event



- (void)getDraftScoreData {
    
        //过滤没有文本的对象
    NSMutableArray *resultArray = [@[] mutableCopy];
    for (SRBookPageTrackItemModel *item in self.items) {
        if (item.track_txt && [item.track_txt length] > 0) {
            [resultArray addObject:item];
        }
    }
    
    if ([resultArray count] > 0) {
        self.items = resultArray;
    } else {
            //没有可读的句子信息
        self.items = @[];
        
        return;
    }
    
    
    NSString *data_id = [NSString stringWithFormat:@"%@_%@", self.bookID, self.catalogueModel.catalogue_id];
    NSArray *dubbingArray = [SRSpeakingDatabaseManager searchMyDraftModelWithDataID:data_id];
    
    if (dubbingArray.count > 0) {
        SRSpeakingTestModel *unpubModel = [dubbingArray firstObject];
        self.speadkingModel = unpubModel;
        self.speadkingModel.page_id = self.catalogueModel.catalogue_id;
        self.speadkingModel.data_id = data_id;
        NSString *sentencesScoreString = unpubModel.sentencesScore;
        NSData *sentenceJSONData = [sentencesScoreString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *sentenceError;
        NSDictionary *sentenceDic = [NSJSONSerialization JSONObjectWithData:sentenceJSONData options:0 error:&sentenceError];
        if (!sentenceError) {
            self.sentenceScoreDict = sentenceDic;
        } else {
            NSLog(@"sentence to dic fail");
        }
        
        NSString *wordsScoreString = unpubModel.wordsScore;
        NSData *wordJSONData = [wordsScoreString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *wordError;
        NSDictionary *wordDic = [NSJSONSerialization JSONObjectWithData:wordJSONData options:0 error:&wordError];
        if (!wordError) {
            NSMutableDictionary * __block resultDic = [[NSMutableDictionary alloc] init];
            [wordDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                NSArray *arr = obj;
                NSMutableArray * __block modelArr = [[NSMutableArray alloc] init];
                [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSDictionary *dic = obj;
                    SREvaluationWordScoreModel *wordModel = [SREvaluationWordScoreModel fromDictionary:dic];
                    if (wordModel) {
                        [modelArr addObject:wordModel];
                    }
                }];
                [resultDic setValue:modelArr forKey:key];
            }];
            self.draftWordScore = resultDic;
        } else {
            NSLog(@"word to dic fail");
        }
		
        self.speadkingModel.user_id = [SRLoginUser userID];
        
        if ([self.items count] > 0 && [sentenceDic count] > 0) {
            WEAKSELF
            [self.items enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                STRONGSELFFor(weakSelf)
                SRBookPageTrackItemModel *recordModel = obj;
                recordModel.isExpand = NO;
                if (recordModel.track_txt && ![recordModel.track_txt isEqualToString:@""]) {
                    NSAttributedString *attrString = [weakSelf makeAttributedEnString:recordModel.track_txt];
                    recordModel.enHeight = [weakSelf calculateAttributedEnHeight:attrString];
                }
                if (recordModel.track_genre && ![recordModel.track_genre isEqualToString:@""]) {
                    NSAttributedString * attributedCnString = [weakSelf makeAttributedCnString:recordModel.track_genre];
                    recordModel.cnHeight = [weakSelf calculateAttributedCnHeight:attributedCnString];
                    recordModel.fullHeight = recordModel.enHeight + recordModel.cnHeight;
                    
                } else {
                    recordModel.fullHeight = recordModel.enHeight + 25;
                }
                NSString *filePath = [FZMCCacheManager audioRecordFilePathWithTrackID:recordModel.track_id pageID:recordModel.page_id bookID:self.bookID];
                if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                    recordModel.hasRecord = YES;
                    weakSelf.recordCount += 1;
                }
                
                recordModel.scoreModel = [strongSelf makeScoreModelsWithTrackID:recordModel.track_id];
            }];
            
            [self updateRecordProgress];
        }
    } else {
    
        self.speadkingModel = [[SRSpeakingTestModel alloc] init];
        self.speadkingModel.data_id = data_id;
        self.speadkingModel.book_id = self.bookID;
        self.speadkingModel.page_id = self.catalogueModel.catalogue_id;

        self.speadkingModel.user_id = [SRLoginUser userID];

        self.speadkingModel.finished = [NSNumber numberWithBool:NO];
        
        WEAKSELF
        [self.items enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            STRONGSELFFor(weakSelf)
            SRBookPageTrackItemModel *recordModel = obj;
            recordModel.isExpand = NO;
            if (recordModel.track_txt && ![recordModel.track_txt isEqualToString:@""]) {
                NSAttributedString *attrString = [weakSelf makeAttributedEnString:recordModel.track_txt];
                recordModel.enHeight = [weakSelf calculateAttributedEnHeight:attrString];
            }
            if (recordModel.track_genre && ![recordModel.track_genre isEqualToString:@""]) {
                NSAttributedString * attributedCnString = [weakSelf makeAttributedCnString:recordModel.track_genre];
                recordModel.cnHeight = [weakSelf calculateAttributedCnHeight:attributedCnString];
                recordModel.fullHeight = recordModel.enHeight + recordModel.cnHeight;
            } else {
                recordModel.fullHeight = recordModel.enHeight + 25;
            }
            NSString *filePath = [FZMCCacheManager audioRecordFilePathWithTrackID:recordModel.track_id pageID:recordModel.page_id bookID:self.bookID];
            if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                recordModel.hasRecord = YES;
            }
        }];

    }
    
//    if ([self.items count] > 0) {
//        SRBookPageTrackItemModel *model = [self.items firstObject];
//        model.isExpand = YES;
//    }
}

- (NSAttributedString *)makeAttributedEnString:(NSString *)enString{
    NSMutableString *mEnString = [enString mutableCopy];
//    if (needExchange > 0) {
        [mEnString replaceOccurrencesOfString:@"，" withString:@"," options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
        [mEnString replaceOccurrencesOfString:@"。" withString:@"." options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
        [mEnString replaceOccurrencesOfString:@"" withString:@"." options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
        [mEnString replaceOccurrencesOfString:@"：" withString:@":" options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
        [mEnString replaceOccurrencesOfString:@"！" withString:@"!" options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
        [mEnString replaceOccurrencesOfString:@"“" withString:@"\"" options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
        [mEnString replaceOccurrencesOfString:@"‘" withString:@"'" options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
        [mEnString replaceOccurrencesOfString:@"？" withString:@"?" options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
        [mEnString replaceOccurrencesOfString:@"、" withString:@"\\" options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
        [mEnString replaceOccurrencesOfString:@"（" withString:@"(" options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
        [mEnString replaceOccurrencesOfString:@"）" withString:@")" options:NSLiteralSearch range:NSMakeRange(0, mEnString.length)];
//    }
    NSString *stringAfterReplace = [NSString stringWithString:mEnString];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5.0f;
    NSDictionary *attributes = @{
                                 NSFontAttributeName : [FZStyleSheet currentStyleSheet].fontOfH3,
                                 NSForegroundColorAttributeName : [FZStyleSheet currentStyleSheet].color_6,
                                 NSParagraphStyleAttributeName : style
                                 };
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:stringAfterReplace attributes:attributes];
    return attrStr;
}

- (NSAttributedString *)makeAttributedCnString:(NSString *)cnString {
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5.0f;
    NSDictionary *attributes = @{
                                 NSFontAttributeName :  [FZStyleSheet currentStyleSheet].fontOfH5,
                                 NSForegroundColorAttributeName : [FZStyleSheet currentStyleSheet].color_6,
                                 NSParagraphStyleAttributeName : style
                                 };
    NSString *finalCN = [NSString stringWithFormat:@"\n\n%@", cnString];
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:finalCN attributes:attributes];
    return attrStr;
}

- (CGFloat)calculateAttributedEnHeight:(NSAttributedString *)enString {
    UITextView *tt = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 47 * 2, CGFLOAT_MAX)];
    tt.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    tt.attributedText = enString;
    CGSize size = [tt sizeThatFits:CGSizeMake(SCREEN_WIDTH - 47 * 2, CGFLOAT_MAX)];
    return size.height;
}

- (CGFloat)calculateAttributedCnHeight:(NSAttributedString *)cnString {
    UITextView *tt = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 47 * 2, CGFLOAT_MAX)];
    tt.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    tt.attributedText = cnString;
    CGSize size = [tt sizeThatFits:CGSizeMake(SCREEN_WIDTH - 47 * 2, CGFLOAT_MAX)];
    return size.height;
}


- (SREvaluationScoreModel *)makeScoreModelsWithTrackID:(NSString *)trackID {
    SREvaluationScoreModel *model = [[SREvaluationScoreModel alloc] init];
    NSDictionary *scoreDic = [self.sentenceScoreDict objectForKey:[NSString stringWithFormat:@"%@", trackID]];
    if (scoreDic && [scoreDic isKindOfClass:[NSDictionary class]] && scoreDic.count > 0) {
        model.originScore = scoreDic[@"total"];
        model.accuracyScore = scoreDic[@"accuracy"];
        model.integrityScore = scoreDic[@"integrity"];
        model.fluencyScore = scoreDic[@"fluency"];
        
//        NSMutableArray * __block wordScoreArr = [[NSMutableArray alloc] init];
        NSArray *wordScores = [self.draftWordScore objectForKey:[NSString stringWithFormat:@"%@", trackID]];
//        [wordScores enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            SREvaluationWordScoreModel *word = obj;
//            SREvaluationWordScoreModel *wordModel = [[FZDubEvaluationWordScoreModel alloc] init];
//            wordModel.word = word.word;
//            wordModel.score = @(word.score);
//            [wordScoreArr addObject:wordModel];
//        }];
		if (wordScores) {
			model.wordScoreArray = [NSArray arrayWithArray:wordScores];
		} else {
			model.wordScoreArray = [[NSMutableArray alloc] init];
		}
		
        return model;
    } else if (scoreDic && [scoreDic isKindOfClass:[NSNumber class]]) {
        model.originScore = (NSNumber *)scoreDic;
        model.accuracyScore = @(-1);
        model.integrityScore = @(-1);
        model.fluencyScore = @(-1);
        
//        NSMutableArray * __block wordScoreArr = [[NSMutableArray alloc] init];
//        NSArray *wordScores = [self.draftWordScore objectForKey:[NSString stringWithFormat:@"%ld", (long)index + 1]];
//        [wordScores enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            FZDubbingWordModel *word = obj;
//            FZDubEvaluationWordScoreModel *wordModel = [[FZDubEvaluationWordScoreModel alloc] init];
//            wordModel.word = word.word;
//            wordModel.score = @(word.score);
//            [wordScoreArr addObject:wordModel];
//        }];
//        model.wordScoreArray = [NSArray arrayWithArray:wordScoreArr];
        return model;
    } else {
        return nil;
    }
}

- (void)calculateScoresToModel {
    NSInteger __block fullScore = 0;
    NSInteger __block fullAccuracyScore = 0;
    NSInteger __block fullIntegrityScore = 0;
    NSInteger __block fullFluencyScore = 0;
    NSMutableDictionary * __block sentencesScoreDict = [[NSMutableDictionary alloc] init];
    NSMutableDictionary * __block wordsScore = [[NSMutableDictionary alloc] init];
    [self.items enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SRBookPageTrackItemModel *model = obj;
        
        if (model.scoreModel) {
            NSInteger sentenceScore = [model.scoreModel.originScore integerValue];
            fullScore += sentenceScore < 0 ? 0 : sentenceScore;
            NSInteger accuracyScore = [model.scoreModel.accuracyScore integerValue];
            fullAccuracyScore += accuracyScore < 0 ? 0 : accuracyScore;
            NSInteger integrityScore = [model.scoreModel.integrityScore integerValue];
            fullIntegrityScore += integrityScore < 0 ? 0 : integrityScore;
            NSInteger fluencyScore = [model.scoreModel.fluencyScore integerValue];
            fullFluencyScore += fluencyScore < 0 ? 0 : fluencyScore;
            
            NSMutableDictionary *senScore = [[NSMutableDictionary alloc] init];
            [senScore setValue:model.scoreModel.originScore forKey:@"total"];
            [senScore setValue:model.scoreModel.accuracyScore forKey:@"accuracy"];
            [senScore setValue:model.scoreModel.integrityScore forKey:@"integrity"];
            [senScore setValue:model.scoreModel.fluencyScore forKey:@"fluency"];
            
            NSString *trackID = [NSString stringWithFormat:@"%@", model.track_id];
            [sentencesScoreDict setValue:senScore forKey:trackID];
            
            NSMutableArray * __block wordArray = [[NSMutableArray alloc] init];
            [model.scoreModel.wordScoreArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                SREvaluationWordScoreModel *wordModel = obj;
                NSDictionary *dic = [wordModel toDictionary];
                [wordArray addObject:dic];
            }];
            [wordsScore setValue:wordArray forKey:model.track_id];
        }
       
    }];
    
    if ([sentencesScoreDict allValues] > 0 && [self.items count] > 0){
        self.speadkingModel.accuracyScore = @(round(fullAccuracyScore / self.items.count));
        self.speadkingModel.integrityScore = @(round(fullIntegrityScore / self.items.count));
        self.speadkingModel.fluencyScore = @(round(fullFluencyScore / self.items.count));
        self.speadkingModel.totalScore = @(round(fullScore / self.items.count));
        NSString *sentenScoreString = @"";
        if (!sentencesScoreDict || sentencesScoreDict.count == 0) {
            sentenScoreString = @"";
        } else {
            NSError *sentenceError;
            NSData *sentenceData = [NSJSONSerialization dataWithJSONObject:sentencesScoreDict options:0 error:&sentenceError];
            if (!sentenceError) {
                NSString *sentenceJSONString = [[NSString alloc] initWithData:sentenceData encoding:NSUTF8StringEncoding];
                sentenScoreString = sentenceJSONString;
            }
        }
        self.speadkingModel.sentencesScore = sentenScoreString;
		
		if (wordsScore) {
			NSError *wordError;
			NSData *wordData = [NSJSONSerialization dataWithJSONObject:wordsScore options:0 error:&wordError];
			if (!wordError) {
				NSString *wrodJSONString = [[NSString alloc] initWithData:wordData encoding:NSUTF8StringEncoding];
				self.speadkingModel.wordsScore = wrodJSONString;
				
			}
		}
        if (self.pageSpeakingTestScoreBlock) {
            self.pageSpeakingTestScoreBlock([self.speadkingModel.totalScore integerValue]);
        }
		
    } else {
        self.speadkingModel.totalScore = @(-1);
        self.speadkingModel.accuracyScore =  @(-1);
        self.speadkingModel.integrityScore = @(-1);
        self.speadkingModel.fluencyScore = @(-1);
        self.speadkingModel.sentencesScore = nil;
    }
}

- (void)saveSpeakingTestModelToDatabase {
    if (self.speadkingModel.sentencesScore && [self.speadkingModel.sentencesScore length] > 0) {
            //有评分信息则保存
        [SRSpeakingDatabaseManager saveMyUnpublishedSpeakingModel:self.speadkingModel];
    }
}

    //判断是否允许使用麦克风7.0新增的方法requestRecordPermission
- (BOOL)canRecord {
    __block BOOL bCanRecord = YES;
//    WEAKSELF
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession requestRecordPermission:^(BOOL granted) {
        if (granted) {
            bCanRecord = YES;
        }
        else {
            bCanRecord = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                
//                WEAKSELF
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您未开启“英语趣点读”访问您的手机麦克风的权限，请在手机的设置中进行开启" cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^(void){
//                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }] otherButtonItems:[RIButtonItem itemWithLabel:@"设置" action:^(void){
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }], nil];
                
                [alertView show];
            });
        }
        
    }];
    
    return bCanRecord;
}


#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self.items count] > 0) {
        return [self.items count] + 1;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row < [self.items count]) {
        
        SRSpeakingTestTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRSpeakingTestTableViewCell forIndexPath:indexPath];
        cell.indexPath = indexPath;
        SRBookPageTrackItemModel *model = self.items[indexPath.row];
        [cell updateCellInfo:model];
        
        WEAKSELF
        cell.touchOriginPlayButtonBlock = ^(SRBookPageTrackItemModel *trackModel, UIButton *sender) {
            [weakSelf onTouchOriginPlayButton:sender trackModel:trackModel];
        };
        
        cell.touchRecodButtonBlock = ^(SRBookPageTrackItemModel *trackModel, UIButton *sender, BOOL isRecording, NSIndexPath *indexPath) {
            [weakSelf onTouchRecordButton:sender trackModel:trackModel isRecording:isRecording indexPath:indexPath];
        };
        
        cell.touchUserRecordPlayButtonBlock = ^(SRBookPageTrackItemModel *trackModel, UIButton *sender) {
            [weakSelf userRecordPlayButton:sender trackModel:trackModel];
        };
        
        cell.touchShareButtonBlock = ^(SRBookPageTrackItemModel *trackModel, UIButton *sender) {
            [weakSelf onTouchShareButton:sender trackModel:trackModel];
        };
        
        cell.touchWordTranslateBlock = ^(NSString *word) {
            [weakSelf showTranslateViewWithWord:word];
        };
        
        
        return cell;
        
    } else {
            //完成按钮；
        SRSpeakingTestDoneTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRSpeakingTestDoneTableViewCell forIndexPath:indexPath];
        WEAKSELF
        cell.touchDoneButtonBlock = ^(id sender) {
            [weakSelf onDoneButtonAction:sender];
        };
        
        return cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row < [self.items count]) {
        SRBookPageTrackItemModel *model = self.items[indexPath.row];
        
        if (model.isExpand) {
            
            CGFloat rowHeight = model.fullHeight + 100 + 140;
            CGFloat maxHeight = (SCREEN_HEIGHT - 64);
            if (rowHeight > maxHeight) {
                return maxHeight;
            }
            
            return rowHeight;
        }
        
        return  15 + 31 + 70;
    }
   
    return 150;
}

#pragma mark - UITableViewDelegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    if (indexPath.row >= [self.items count]) {
        return;
    }
    
    if (self.targetIndexPath && self.targetIndexPath.row == indexPath.row) {
        return;
    }
    
    SRBookPageTrackItemModel *model = self.items[indexPath.row];
    model.isExpand = YES;
    
    if (self.targetIndexPath) {
        SRBookPageTrackItemModel *lastModel = self.items[self.targetIndexPath.row];
        lastModel.isExpand = NO;
        
        [self.tableView reloadRowsAtIndexPaths:@[self.targetIndexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
	[self.scoreHeaderView updateCellInfoForScore:model.scoreModel];
	[self.scoreHeaderView setIndex:indexPath.row];

    self.targetIndexPath = indexPath;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
    [self onTouchOriginPlayButton:nil trackModel:model];

}


#pragma mark - Handle touch event

- (void)countRecordTrack {
    NSInteger count = 0;
    for (SRBookPageTrackItemModel *item in self.items) {
        if (item.hasRecord) {
            ++ count;
        }
    }
    
    self.recordCount = count;
    
    [self updateRecordProgress];
}

- (void)updateRecordProgress {
    self.title = [NSString stringWithFormat:@"%@ (%lu/%lu)", self.catalogueModel.title, self.recordCount, (unsigned long)[self.items count]];
}


#pragma mark - Event
    //播放原音
- (void)onTouchOriginPlayButton:(id)sender trackModel:(SRBookPageTrackItemModel *)trackModel {
    
    NSString *mp3Path = [FZMCCacheManager mp3PathWithName:trackModel.mp3name bookID:self.bookID];
    [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFilePath:mp3Path startTime:[trackModel.track_austart doubleValue] endTime:[trackModel.track_auend doubleValue]];
    [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
    
}
    //录音
- (void)onTouchRecordButton:(id)sender trackModel:(SRBookPageTrackItemModel *)trackModel isRecording:(BOOL)isRecording indexPath:(NSIndexPath *)indexPath{
    self.targetIndexPath = indexPath;
    [[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];

    if (!isRecording) {
            //停止
        [[SRAudioPlayerManager sharedInstance] stopRecorder];
    }
//    } else {
            //开始录音
        trackModel.hasRecord = YES;
        self.isEvaluating = YES;
        NSString *filePath = [FZMCCacheManager audioRecordFilePathWithTrackID:trackModel.track_id pageID:trackModel.page_id bookID:self.bookID];
        [FZMCCacheManager removeFileCache:filePath];
        NSString *mp3Path = [FZMCCacheManager recordMp3FilePathWithTrackID:trackModel.track_id pageID:trackModel.page_id bookID:self.bookID];
        [FZMCCacheManager removeFileCache:mp3Path];//删除上传的mp3文件，已经重新录音了，需要重新转化

        [[SRAudioPlayerManager sharedInstance] prepareToRecorderOutputUrl:filePath];
        
        CGFloat duration = [trackModel.track_auend floatValue] - [trackModel.track_austart floatValue];
        
//        [self.evaluationManager startRecordWithText:trackModel.track_txt textType:SRSpeakingEvaluationTextTypeEnglish bonusArray:nil];
    [self startOralWithText:trackModel.track_txt];

        [[SRAudioPlayerManager sharedInstance] beginRecorderForDuration:duration];
        
        WEAKSELF
        [SRAudioPlayerManager sharedInstance].audioRecorderBeginBlock = ^(id target) {
            
        };

        
        [SRAudioPlayerManager sharedInstance].audioRecorderProgressBlock = ^(CGFloat progress) {
//            NSLog(@"audioRecorderProgressBlock:%f", progress);
            SRSpeakingTestTableViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:weakSelf.targetIndexPath];
            if (cell) {
                [cell setProgress:progress];
            }
        };
        
        [SRAudioPlayerManager sharedInstance].audioRecorderCompletedBlock = ^(BOOL finish) {
            NSLog(@"audioPlayerCompletedBlock:%d", finish);
            
            if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus != AFNetworkReachabilityStatusNotReachable && weakSelf.isEvaluating) {
                    //网络不可用
//                [weakSelf stopProgressHUD];
                [weakSelf startProgressHUDWithText:@"评分中..."];
            }
//            [weakSelf.evaluationManager stopRecord];
            [weakSelf stopOral];

            SRSpeakingTestTableViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:weakSelf.targetIndexPath];
            if (cell) {
                [cell setIsRecording:NO];
            }
        };
    
        [SRAudioPlayerManager sharedInstance].audioRecorderFailureBlock = ^(NSString *message) {
            weakSelf.isEvaluating = NO;
            [weakSelf showHUDErrorMessage:message];
            [weakSelf stopOral];
            SRSpeakingTestTableViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:weakSelf.targetIndexPath];
            if (cell) {
                [cell setIsRecording:NO];
            }
        };
    
    
    [self countRecordTrack];
    
//        NSString *data_id = [NSString stringWithFormat:@"%@_%@_%@", self.bookID, trackModel.page_id, trackModel.track_id];
//        [SRSpeakingDatabaseManager removeSpeakingTrackModelWithDataID:data_id];
//    }
}
    //播放用户录音
- (void)userRecordPlayButton:(id)sender trackModel:(SRBookPageTrackItemModel *)trackModel{
    NSString *filePath = [FZMCCacheManager audioRecordFilePathWithTrackID:trackModel.track_id pageID:trackModel.page_id bookID:self.bookID];
    [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFilePath:filePath];
    [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
}

- (void)onTouchShareButton:(id)sender trackModel:(SRBookPageTrackItemModel *)trackModel{
    self.shareTrackModel = trackModel;
    
    if ([SRLoginManager sharedManager].hasLogin) {
        
        NSString *data_id = [NSString stringWithFormat:@"%@_%@_%@", self.bookID, trackModel.page_id, trackModel.track_id];
        NSArray *resultArray = [SRSpeakingDatabaseManager searchSpeakingTrackModelWithDataID:data_id];
        if ([resultArray count] > 0) {
            SRBookPageTrackItemModel *existModel = [resultArray objectAtIndex:0];
            if (existModel && existModel.share_url && [existModel.share_url length] > 0) {
                [self shareTrackModelWithShareUrl:existModel.share_url];
            } else {
                [self uploadAudioRecordToQiniuWithTrackModel:trackModel];
            }
        } else {
            [self uploadAudioRecordToQiniuWithTrackModel:trackModel];
        }
    }else {
            //提示登录
        [[SRLoginManager sharedManager] showLoginViewSinceController:self];
    }
    
}

#pragma mark - evaluation delegate

//- (void)speakingEvaluationSuccess:(SREvaluationScoreModel *)scoreModel{
//    self.isEvaluating = NO;
//    [self stopProgressHUD];
//
//    if (scoreModel) {
//        SRSpeakingTestTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.targetIndexPath];
//        if (cell) {
//            [cell setScoreModel:scoreModel];
//        }
//    }
//
//}
//
//- (void)speakingEvaluationStatusChanged:(SRSpeakingEvaluationStatus)evaluationStatus message:(NSString *)message {
//        // 只有讯飞返回结果之后（无论成功失败），才能滚动table
//    [self stopProgressHUD];
//
//    if (evaluationStatus == SRSpeakingEvaluationStatusSuccess || evaluationStatus == SRSpeakingEvaluationStatusFail || evaluationStatus == SRSpeakingEvaluationStatusStartRecordFail || evaluationStatus == SRSpeakingEvaluationStatusStopRecordFail || evaluationStatus == SRSpeakingEvaluationStatusNetworkError) {
////        self.rootTable.scrollEnabled = YES;
////        self.recordButton.enabled = YES;
//        self.isEvaluating = NO;
//    }
//    
//    if (evaluationStatus == SRSpeakingEvaluationStatusStopRecordFail || evaluationStatus == SRSpeakingEvaluationStatusStartRecordFail || evaluationStatus == SRSpeakingEvaluationStatusFail || evaluationStatus == SRSpeakingEvaluationStatusNetworkError) {
//            //错误提示
//        if (message) {
//            [self showHUDErrorMessage:message];
//        }
//    }
//}

#pragma mark - Upload Audio and share

- (void)uploadAudioRecordToQiniuWithTrackModel:(SRBookPageTrackItemModel *)trackModel {
    
    NSString *filePath = [FZMCCacheManager audioRecordFilePathWithTrackID:trackModel.track_id pageID:trackModel.page_id bookID:self.bookID];

    
    if (![SRLoginUser uploadToken]) {
        [self showHUDErrorMessage:@"音频上传失败uploadToken不存在"];
        return;
    }
    
    [self startProgressHUDWithText:@"正在上传..."];

    NSString *audioPrefixName = [NSString stringWithFormat:@"%@_%@_%@", self.bookID, trackModel.page_id, trackModel.track_id];
    NSString *audioFileName = [NSString stringWithFormat:@"Record_%@_%@.mp3", audioPrefixName, [self dateString]];
    
        //指定新建文件夹路径
    NSString *mp3Path = [FZMCCacheManager recordMp3FilePathWithTrackID:trackModel.track_id pageID:trackModel.page_id bookID:self.bookID];
    

//    NSString *existFilePath = [FZMCCacheManager isExistMp3FilePathWithTrackID:trackModel.track_id pageID:self.pageModel.pageID bookID:self.bookID];
//    if (existFilePath && [existFilePath length] > 0) {
//            //已经存在了
//        self.mp3FilePath = existFilePath;
//        self.audioFileName = [existFilePath lastPathComponent];
//        [self convertMp3Success];
//    } else {
        self.audioFileName = audioFileName;
        self.mp3FilePath = mp3Path;
        
        [self covertCaf:filePath toMp3:mp3Path];
//    }
    
}

- (NSString *)dateString {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";
//    NSString *dayString = [dateFormatter stringFromDate:[NSDate date]];
    NSString *timeInterval = [NSString stringWithFormat:@"%lld", (long long)[NSDate timeIntervalSince1970]];
    return [NSString stringWithFormat:@"uid%@_%@", [SRLoginUser userID], timeInterval];
}

- (void)uploadAudioInfoToServerWithTrackID:(NSString *)trackID pageID:(NSString *)pageID fileName:(NSString *)fileName score:(NSInteger)score {
    WEAKSELF
    NSString *data_id = [NSString stringWithFormat:@"%@_%@_%@", weakSelf.bookID, pageID, trackID];

    self.shareTrackModel.audio_name = fileName;
    self.shareTrackModel.data_id = data_id;
    self.shareTrackModel.book_id = self.bookID;
	
	NSString *bookID = self.bookID;
	if ([bookID isEqualToString:@"0"]) {
		bookID = @"1";
	}
	
    [SRAlbumService addUserAudioRecordWithTrackID:trackID bookID:bookID pageID:pageID score:score audioFileName:fileName successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
//            "show_track_id": 2,
//            "share_url": "http://120.27.236.36:8082/showTrack/share/id/MDAwMDAwMDAwMIbNdKE"
            NSString *shareURL = responseDataObject[@"share_url"];
            [SRSpeakingDatabaseManager saveSpeakingTrackModel:weakSelf.shareTrackModel fileName:fileName shareUrl:shareURL];
            
            [weakSelf shareTrackModelWithShareUrl:shareURL];
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
        
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDErrorMessage:@"保存录音信息到服务器失败"];

    }];
}

- (void)uploadAudioWorkToServerWithCatalogueID:(NSString *)catalogueID fileName:(NSString *)fileName score:(NSInteger)score {
    WEAKSELF
    NSString *data_id = [NSString stringWithFormat:@"%@_%@", weakSelf.bookID, catalogueID];
    NSString *trackTimes = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.trackTimesDict options:NSJSONWritingPrettyPrinted error:&error];
    if (! jsonData) {
            //转化失败
    } else {
        trackTimes = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    self.shareTrackModel.audio_name = fileName;
    self.shareTrackModel.data_id = data_id;
    self.shareTrackModel.book_id = self.bookID;
	NSString *bookID = self.bookID;
	if ([bookID isEqualToString:@"0"]) {
		bookID = @"1";
	}
	
	
    [SRAlbumService addUserAudioWorkWithCatalogueID:self.catalogueModel.catalogue_id bookID:bookID score:score audioFileName:fileName audioTrack:trackTimes group_id:self.groupID task_id:self.taskID successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
                //            "show_track_id": 2,
                //            "share_url": "http://120.27.236.36:8082/showTrack/share/id/MDAwMDAwMDAwMIbNdKE"
            
                //若是作业完成直接返回
            if (weakSelf.groupID && weakSelf.taskID) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kSRFinishTaskDidSuccessNotification object:nil];
                [weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:1];
            }
            
            NSString *shareURL = responseDataObject[@"share_url"];
//            weakSelf.shareURL = shareURL;
            weakSelf.uploadWorkShareURL = shareURL;
            weakSelf.uploadWorkID = [NSString stringWithFormat:@"%@", responseDataObject[@"show_id"]];
            [weakSelf showShareView];
//            [SRSpeakingDatabaseManager saveSpeakingTrackModel:weakSelf.shareTrackModel fileName:fileName shareUrl:shareURL];
            
//            [weakSelf shareTrackModelWithShareUrl:shareURL];
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
        
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDErrorMessage:@"保存录音信息到服务器失败"];
        
    }];
}

- (void)shareTrackModelWithShareUrl:(NSString *)shareURL {
    WEAKSELF
    FZCommonShareContent *shareContent = [[FZCommonShareContent alloc] init];
    shareContent.dataType = FZCommonShareContentTypeWebpage;
    NSString *nickname = [SRLoginUser nickname];
    NSString *bookName = self.bookName;
    shareContent.desc = [NSString stringWithFormat:@"%@的录音短句《%@》快来听一下吧！", nickname, bookName];
    shareContent.title = @"专为小学生设计的智能学习机";
    UIImage *image = [UIImage imageNamed:@"appLogo"];
    shareContent.thumbnailData = UIImagePNGRepresentation(image);
    
    shareContent.webpageUrl = shareURL;
    [[FZCommonShare sharedInstance] shareFromViewController:self content:shareContent fullCompletion:^(FZCommonShareSocialSNSType socialType, FZCommonShareResponseState responseState, NSString *errorMessage) {
        if (responseState == FZCommonShareResponseStateSuccess) {
            [weakSelf showHUDHintWithText:@"分享成功"];
        } else if (responseState == FZCommonShareResponseStateNotInstalled) {
            [weakSelf showHUDHintWithText:[NSString stringWithFormat:@"您的手机不支持分享到该APP"]];
        }
    }];
}

- (void)shareTrackModelWithShareUrl:(NSString *)shareURL snsType:(FZCommonShareSocialSNSType)socialType {
    WEAKSELF
    FZCommonShareContent *shareContent = [[FZCommonShareContent alloc] init];
    shareContent.dataType = FZCommonShareContentTypeWebpage;
    NSString *nickname = [SRLoginUser nickname];
    NSString *bookName = self.bookName;
    shareContent.desc = [NSString stringWithFormat:@"%@的录音作品《%@》快来听一下吧！", nickname, bookName];
    shareContent.title = @"专为小学生设计的智能学习机";
    UIImage *image = [UIImage imageNamed:@"appLogo"];
    shareContent.thumbnailData = UIImagePNGRepresentation(image);
    
    shareContent.webpageUrl = shareURL;
    
    [[FZCommonShare sharedInstance] shareContent:shareContent type:socialType completion:^(FZCommonShareResponseState responseState, NSString *errorMessage) {
        if (responseState == FZCommonShareResponseStateSuccess) {
            [weakSelf showHUDHintWithText:@"分享成功"];
        } else if (responseState == FZCommonShareResponseStateNotInstalled) {
            [weakSelf showHUDHintWithText:[NSString stringWithFormat:@"您的手机不支持分享到该APP"]];
        }
    }];
}

- (void)shareAudioWorkWithShareUrl:(NSString *)shareURL workID:(NSString *)workID snsType:(FZCommonShareSocialSNSType)socialType {
    WEAKSELF
    FZCommonShareContent *shareContent = [[FZCommonShareContent alloc] init];
    shareContent.dataType = FZCommonShareContentTypeWebpage;
    NSString *nickname = [SRLoginUser nickname];
    NSString *bookName = self.bookName;
    shareContent.desc = [NSString stringWithFormat:@"%@的录音作品《%@》快来听一下吧！", nickname, bookName];
    shareContent.title = @"专为小学生设计的智能学习机";
    UIImage *image = [UIImage imageNamed:@"appLogo"];
    shareContent.thumbnailData = UIImagePNGRepresentation(image);
    
    shareContent.webpageUrl = shareURL;
    
    [[FZCommonShare sharedInstance] shareContent:shareContent type:socialType completion:^(FZCommonShareResponseState responseState, NSString *errorMessage) {
        if (responseState == FZCommonShareResponseStateSuccess) {
            [weakSelf showHUDHintWithText:@"分享成功"];
            
            [weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:1];
        } else if (responseState == FZCommonShareResponseStateNotInstalled) {
            [weakSelf showHUDHintWithText:[NSString stringWithFormat:@"您的手机不支持分享到该APP"]];
        }
    }];
}

#pragma mark - Covert to Mp3

- (void)covertCaf:(NSString *)cafFilePath toMp3:(NSString *)mp3FilePath {
    @try {
        int read, write;
        
        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source
        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 44100);
//        lame_set_in_samplerate(lame, 11025.0 * 2);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
        [self performSelectorOnMainThread:@selector(convertMp3Failure)
                               withObject:nil
                            waitUntilDone:YES];
    }
    @finally {
        [self performSelectorOnMainThread:@selector(convertMp3Success)
                               withObject:nil
                            waitUntilDone:YES];
    }
}

- (void)convertMp3Failure {
    [self stopProgressHUD];
    
    NSString *message = [NSString stringWithFormat:@"录音转化为mp3 失败"];
    [self showHUDErrorMessage:message];
}

- (void)convertMp3Success {
    [self stopProgressHUD];
        //开始上传进度条
    [self updateHUDgrogress:MBProgressHUDModeDeterminate labelText:@"上传录音..."];
    WEAKSELF
        //上传图片到七牛云端
    [[SRUploadQiniuManager sharedInstance] uploadFileToQiNiuForPath:self.mp3FilePath key:self.audioFileName uploadToken:[SRLoginUser uploadToken] UploadPercent:^(NSString *key, float percent) {
        CGFloat progress = MIN(percent, 1.0);
        [weakSelf updateMyProgressTask:progress];
        
    } responseBlock:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (info.isOK) {
                //上传成功
            
            if (weakSelf.isComposeWork) {
                [weakSelf uploadAudioWorkToServerWithCatalogueID:weakSelf.catalogueModel.catalogue_id fileName:weakSelf.audioFileName score:weakSelf.workScore];
            } else {
            
                [weakSelf uploadAudioInfoToServerWithTrackID:weakSelf.shareTrackModel.track_id pageID:weakSelf.shareTrackModel.page_id fileName:weakSelf.audioFileName score:[weakSelf.shareTrackModel.scoreModel.originScore integerValue]];
            }
            
        } else {
                //上传数据失败
//            NSLog(@"上传文件失败：%@", resp);
            [weakSelf stopProgressHUD];
            NSString *message = [NSString stringWithFormat:@"录音上传失败ErrorCode(%d):%@", info.statusCode, resp];

            if (info.statusCode == 401) {
                    //token失效过期，提示重新登录
                message = [NSString stringWithFormat:@"认证过期，请重新登录\n录音上传失败ErrorCode(%d):%@", info.statusCode, resp];
                [weakSelf showHUDErrorMessage:message];
                
                [weakSelf performSelector:@selector(showLoginViewController) withObject:nil afterDelay:1];

            } else {
                [weakSelf showHUDErrorMessage:message];

            }
        }
    }];
}

- (void)showLoginViewController {
    [[SRLoginManager sharedManager] logout];
    [[SRLoginManager sharedManager] showLoginViewSinceController:self];
}

#pragma mark - Translate Word

- (void)showTranslateViewWithWord:(NSString *)word {
    
    if (word && [word length] > 0) {
        [self.wordTranslateView resetTranslateView];
        self.wordTranslateBgView.hidden = NO;
        self.wordTranslateView.hidden = NO;
        self.wordTranslateView.word = word;
        [self.wordTranslateView playWordVoiceWithWord:word];
        
        [self translateYoudaoAPIForWord:word];
    }
}

- (void)hideTranslateView {
    self.wordTranslateBgView.hidden = YES;
    self.wordTranslateView.hidden = YES;
}

- (void)translateYoudaoAPIForWord:(NSString *)word {
    WEAKSELF;
    
        //付费版本
//    NSString *urlString = [NSString stringWithFormat:@"http://fanyi.youdao.com/paidapi/fanyiapi?key=1105196212&type=data&doctype=json&version=2.0&q=%@",word];
        //免费版本
    NSString *urlString = [NSString stringWithFormat:@"http://fanyi.youdao.com/openapi.do?keyfrom=yingyuqudiandu&key=1105196212&type=data&doctype=json&version=1.1&q=%@",word];

    [[SRNetWorkManager sharedInstance] GETFromThirdServerWithUrl:urlString parameters:nil responseDtoClassType:[SRYoudaoTranslateRootModel class] success:^(id responseObject) {
        if (responseObject) {
            SRYoudaoTranslateRootModel *rootModel = responseObject;
            if (rootModel.basicModel) {
                [weakSelf updateTranslateView:rootModel.basicModel];
            }
            
        }
    } failure:^(id responseObject, NSError *error) {
//        if (error) {
//            
//        }
    }];
}

- (void)updateTranslateView:(SRYoudaoTranslateBasicModel *)basicModel {
    [self.wordTranslateView updateTranslateInfo:basicModel];
}

#pragma mark - Compose Audio Work -

- (void)onDoneButtonAction:(id)sender {
        //若没有登录则需要登录再合成并上传
    if ([SRLoginManager sharedManager].hasLogin) {
        self.isComposeWork = YES;
        [self composeAudioCafFiles];
    } else {
            //登录
        [[SRLoginManager sharedManager] showLoginViewSinceController:self];
    }
//    [self showShareView];
}
    //合成多个caf录音文件
- (void)composeAudioCafFiles{
    NSString *outPath = [FZMCCacheManager recordComposeAudioFilePathWithCatalogueID:self.catalogueModel.catalogue_id bookID:self.bookID];
    NSMutableArray *cafFiles = [NSMutableArray array];
    NSMutableDictionary *trackTimesDict = [NSMutableDictionary dictionaryWithCapacity:3];
    NSTimeInterval currentTime = 0;
    NSInteger allSentanceScore = 0;
    for (int i = 0; i < [self.items count]; ++ i) {
        SRBookPageTrackItemModel *trackModel = self.items[i];
        NSString *filePath = [FZMCCacheManager audioRecordFilePathWithTrackID:trackModel.track_id pageID:trackModel.page_id bookID:self.bookID];
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
            NSURL *cafURL = [NSURL fileURLWithPath:filePath];
            [cafFiles addObject:cafURL];
            
                //计算时间
            NSTimeInterval trackTime = [trackModel.track_auend doubleValue] - [trackModel.track_austart doubleValue];
            NSString *timeString = [NSString stringWithFormat:@"%.2f,%.2f", currentTime, currentTime + trackTime];
            NSString *trackID = [NSString stringWithFormat:@"%@", trackModel.track_id];
            [trackTimesDict setValue:timeString forKey:trackID];
            
            currentTime += trackTime;
            
                //计算总分
            if (trackModel.scoreModel) {
                allSentanceScore += [trackModel.scoreModel.originScore integerValue];
            }
        }
    }
    
    self.workScore = (CGFloat)allSentanceScore / [self.items count];
    self.trackTimesDict = trackTimesDict;
    
    if ([cafFiles count] > 0) {
        NSURL *outputURL = [NSURL fileURLWithPath:outPath];

        WEAKSELF
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSDate *startDate = [NSDate date];
            NSTimeInterval startTime = [startDate timeIntervalSince1970];
            NSLog(@"composeAduio Time start:%f", startTime);
            [weakSelf startProgressHUDWithText:@"合成音频..."];
            BOOL success = [AudioMerger mergeAudioFiles:cafFiles outputURL:outputURL];
            NSLog(@"mergeAudioFiles success : %d",success);
            NSDate *endDate = [NSDate date];
            NSTimeInterval endTime = [endDate timeIntervalSince1970];
            NSLog(@"composeAduio Time audioTrack end:%f-----distant:%f", endTime, (endTime - startTime));
            
            if (success) {
//                [weakSelf showHUDHintWithText:@"合成音频成功"];
//                [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFilePath:outPath];
//                [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
                
                NSString *mp3FilePath = [FZMCCacheManager recordMp3AudioFilePathWithCatalogueID:weakSelf.catalogueModel.catalogue_id bookID:weakSelf.bookID];
                weakSelf.mp3FilePath = mp3FilePath;
                weakSelf.audioFileName = [mp3FilePath lastPathComponent];
                [weakSelf covertCaf:outPath toMp3:mp3FilePath];
                
            } else {
                [weakSelf stopProgressHUD];
                [weakSelf showHUDHintWithText:@"合成音频失败"];
            }
            
           
        });
    } else {
        [self showHUDHintWithText:@"没有音频合成， 请继续录音"];
    }
}

- (void)composeAudio {
    [self startProgressHUD];

    CMTime currentTime = kCMTimeZero;
    CMTime audioTime = currentTime;
    AVMutableComposition *composition = [AVMutableComposition composition];
    
    NSDate *startDate = [NSDate date];
    NSTimeInterval startTime = [startDate timeIntervalSince1970];
    NSLog(@"composeAduio Time start:%f", startTime);
    
    for (int i = 0; i < [self.items count]; ++ i) {
        SRBookPageTrackItemModel *trackModel = self.items[i];
        NSString *filePath = [FZMCCacheManager audioRecordFilePathWithTrackID:trackModel.track_id pageID:trackModel.page_id bookID:self.bookID];
        if (filePath) {
            NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
            AVAsset *asset = [AVAsset assetWithURL:fileUrl];
            if (asset) {
                NSArray *audioAssetTracks = [asset tracksWithMediaType:AVMediaTypeAudio];
                    //    NSArray *videoAssetTracks = [asset tracksWithMediaType:AVMediaTypeVideo];
                AVMutableCompositionTrack *audioTrack = nil;
                    //    AVMutableCompositionTrack *videoTrack = nil;
                
                CMTime maxBounds = kCMTimeInvalid;
                
                for (AVAssetTrack *audioAssetTrack in audioAssetTracks) {
                    if (audioTrack == nil) {
                        NSArray *audioTracks = [composition tracksWithMediaType:AVMediaTypeAudio];
                        
                        if (audioTracks.count > 0) {
                            audioTrack = [audioTracks firstObject];
                        } else {
                            audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
                        }
                    }
                    
                    audioTime = [self appendTrack:audioAssetTrack toCompositionTrack:audioTrack atTime:audioTime withBounds:maxBounds];
                }
                
                currentTime = composition.duration;
            }

        }
        
    }

    if (CMTimeGetSeconds(currentTime) < 0.1) {
        [self stopProgressHUD];
        [self showHUDHintWithText:@"没有音频合成， 请继续录音"];
        return;
    }
    
    
    WEAKSELF
    NSDate *endDate = [NSDate date];
    NSTimeInterval endTime = [endDate timeIntervalSince1970];
    NSLog(@"composeAduio Time audioTrack end:%f-----distant:%f", endTime, (endTime - startTime));
    
    NSString *composeAudioFilePath = [FZMCCacheManager recordComposeAudioFilePathWithCatalogueID:self.catalogueModel.catalogue_id bookID:self.bookID];
    
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:composition           presetName:AVAssetExportPresetAppleM4A];
//    exporter.videoComposition = composition;
    
    exporter.outputURL = [NSURL fileURLWithPath:composeAudioFilePath];
    
    exporter.outputFileType = AVFileTypeAppleM4A;//@"com.apple.m4a-audio";
    exporter.shouldOptimizeForNetworkUse = YES;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        [weakSelf stopProgressHUD];
        if (exporter.error) {
                //...
            NSLog(@"导出音频错误：%@ ", exporter.error);
            [weakSelf showHUDErrorMessage:@"导出合成音频失败"];
        }else{
                //...
            [weakSelf showHUDErrorMessage:@"合成音频成功"];
            NSDate *exportDate = [NSDate date];
            NSTimeInterval exportTime = [exportDate timeIntervalSince1970];
            NSLog(@"composeAduio Time export file end:%f-----distant:%f", exportTime, (exportTime - startTime));
            
            NSString *mp3FilePath = [FZMCCacheManager recordMp3AudioFilePathWithCatalogueID:weakSelf.catalogueModel.catalogue_id bookID:weakSelf.bookID];
            weakSelf.mp3FilePath = mp3FilePath;
            
            [weakSelf covertCaf:composeAudioFilePath toMp3:mp3FilePath];
            
//            [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFilePath:composeAudioFilePath];
//            [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
        }
    }];
 
}


- (CMTime)appendTrack:(AVAssetTrack *)track toCompositionTrack:(AVMutableCompositionTrack *)compositionTrack atTime:(CMTime)time withBounds:(CMTime)bounds {
    CMTimeRange timeRange = track.timeRange;
    time = CMTimeAdd(time, timeRange.start);
    
    if (CMTIME_IS_VALID(bounds)) {
        CMTime currentBounds = CMTimeAdd(time, timeRange.duration);
        
        if (CMTIME_COMPARE_INLINE(currentBounds, >, bounds)) {
            timeRange = CMTimeRangeMake(timeRange.start, CMTimeSubtract(timeRange.duration, CMTimeSubtract(currentBounds, bounds)));
        }
    }
    
    if (CMTIME_COMPARE_INLINE(timeRange.duration, >, kCMTimeZero)) {
        NSError *error = nil;
        [compositionTrack insertTimeRange:timeRange ofTrack:track atTime:time error:&error];
        
        if (error != nil) {
            NSLog(@"Failed to insert append %@ track: %@", compositionTrack.mediaType, error);
        } else {
                //        NSLog(@"Inserted %@ at %fs (%fs -> %fs)", track.mediaType, CMTimeGetSeconds(time), CMTimeGetSeconds(timeRange.start), CMTimeGetSeconds(timeRange.duration));
        }
        
        return CMTimeAdd(time, timeRange.duration);
    }
    
    return time;
}

- (void)showRecordWork {
    SRWorkDetailViewController *vc = [[SRWorkDetailViewController alloc] init];
    vc.show_id = self.uploadWorkID;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showShareView {
    
    self.shareBackgroundView.frame = self.view.bounds;
    [self.view bringSubviewToFront:self.shareBackgroundView];
    
    [self.shareBackgroundView addSubview:self.popShareView];
    self.popShareView.center = CGPointMake(SCREEN_WIDTH / 2.0, CGRectGetHeight(self.shareBackgroundView.frame) / 2);
    
    self.shareBackgroundView.hidden = NO;
    
}
- (void)hideShareView {
    self.shareBackgroundView.hidden = YES;
}


#pragma mark - oralEvaluating
    //开始评测
- (void)startOralWithText:(NSString *)text {
//    [_field resignFirstResponder];
//    if (_field.text.length == 0) {
//        return;
//    }
//    
//    [self startAnimation];
    SSOralEvaluatingConfig *config = [[SSOralEvaluatingConfig alloc]init];
    config.oralType = OralTypeSentence;
    config.oralContent = text;
    [[SSOralEvaluatingManager shareManager] startEvaluateOralWithConfig:config];
}
    //结束评测
- (void)stopOral {
//    [self stopAnimation];
    [[SSOralEvaluatingManager shareManager] stopEvaluate];
}

#pragma mark - OralEvaluatingManagerDelegate

- (void)oralEvaluatingDidEndWithResult:(NSDictionary *)result isLast:(BOOL)isLast {
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
    self.isEvaluating = NO;
    [self stopProgressHUD];
    
	NSDictionary *resultDict = result[@"result"];
    if (resultDict) {
        NSNumber *scoreString = resultDict[@"overall"];
        SREvaluationScoreModel *scoreModel = [[SREvaluationScoreModel alloc] init];
        scoreModel.originScore = [NSNumber numberWithInteger:[scoreString integerValue]];
		
//		FZDubEvaluationScoreModel *scoreModel = [[FZDubEvaluationScoreModel alloc] init];
		scoreModel.chivoxToken = result[@"tokenId"];
//		NSNumber *totalScore = resultDict[@"overall"];
//		scoreModel.originScore = totalScore;
		scoreModel.totalScore = scoreString;//[self bonusTotalScore:totalScore];
		scoreModel.accuracyScore = resultDict[@"accuracy"];
		scoreModel.integrityScore = resultDict[@"integrity"];
		NSDictionary *fluencyDic = resultDict[@"fluency"];
		scoreModel.fluencyScore = fluencyDic[@"overall"];
		NSArray *wordsArr = resultDict[@"details"];
		NSMutableArray * __block wordScoreArr = [[NSMutableArray alloc] init];
		if (wordsArr && wordsArr.count > 0) {
			[wordsArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
				NSDictionary *wordDic = obj;
				SREvaluationWordScoreModel *wordScoreModel = [[SREvaluationWordScoreModel alloc] init];
				wordScoreModel.word = wordDic[@"char"];
				wordScoreModel.score = wordDic[@"score"];
				[wordScoreArr addObject:wordScoreModel];
			}];
			scoreModel.wordScoreArray = wordScoreArr;
		}
		
        if (scoreModel) {
            SRSpeakingTestTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.targetIndexPath];
            if (cell) {
                [cell setScoreModel:scoreModel];
            }
			
			[self.scoreHeaderView updateCellInfoForScore:scoreModel];
        }
    } else {
            //错误发生
        NSString *errId = result[@"errId"];
        NSString *errorMessage = result[@"error"];
        NSString *message = [NSString stringWithFormat:@"评分错误：%@_%@", errId, errorMessage];
        [self showHUDErrorMessage:message];
    }
    
}

- (void)oralEvaluatingDidEndError:(NSError *)error {
//    _resultTextView.text = error.localizedDescription;
    
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self stopProgressHUD];
    self.isEvaluating = NO;
    NSLog(@"%@",error);
    if (error) {
        NSString *message = [NSString stringWithFormat:@"评分错误：%@", error.localizedDescription];
        [self showHUDErrorMessage:message];
    } else {
        [self showHUDErrorMessage:@"评分错误"];
    }
    
    [[SSOralEvaluatingManager shareManager] cancelEvaluate];
}

- (void)oralEvaluatingDidStop {
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

- (void)oralEvaluatingDidVADBackTimeOut {
    NSLog(@"后置超时");
//    [self stopAnimation];
    self.isEvaluating = NO;
    [self stopProgressHUD];
    [[SSOralEvaluatingManager shareManager] stopEvaluate];
}

- (void)oralEvaluatingDidVADFrontTimeOut {
    NSLog(@"前置超时");
    self.isEvaluating = NO;
    [self stopProgressHUD];
//    [self stopAnimation];
    [[SSOralEvaluatingManager shareManager] cancelEvaluate];
}


@end
